<template>
  <el-dialog
    :model-value="dialogVisible"
    :title="dialogTitle"
    width="45%"
    @close="handleClose"
  >
    <el-form ref="formRef" :model="form" label-width="100px" :rules="rules">
      <el-form-item label="剧集名" prop="title">
        <el-input v-model="form.title" />
      </el-form-item>

      <el-form-item label="剧集数" prop="index">
        <el-input v-model="form.index" />
      </el-form-item>
      <el-form-item label="剧集源" prop="url">
        <el-input v-model="form.url" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span
        class="dialog-footer"
        style="
          margin-left: 8%;
          margin-right: 8%;
          justify-content: space-between;
          display: flex;
        "
      >
        <el-button type="warning" @click="handleClose" plain>取消</el-button>
        <el-button type="primary" @click="handleConfirm" plain>确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineEmits, ref, defineProps, watch } from 'vue'
import { addEpisode, editEpisode } from '@/api/episode'
import { ElMessage } from 'element-plus'

const props = defineProps({
  dialogTitle: {
    default: '',
    type: String,
    required: true
  },
  dialogTableVable: {
    type: Object,
    default: () => {}
  }
})

const emits = defineEmits(['update:modelValue', 'initGetEpisodesList'])

const handleClose = () => {
  emits('update:modelValue', false)
}

const handleConfirm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      props.dialogTitle === '添加剧集'
        ? await addEpisode(form.value)
        : await editEpisode(form.value)
      ElMessage({
        message: props.dialogTitle === '添加剧集' ? '新增成功' : '修改成功',
        type: 'success'
      })
      emits('initGetEpisodesList')
      handleClose()
    } else {
      return false
    }
  })
}

const formRef = ref(null)

const form = ref({
  id: 0,
  animeId: 0,
  title: '',
  index: 0,
  url: ''
})

console.log(form.value)

const rules = ref({
  title: [
    {
      required: true,
      pattern: '[^ \x20]+',
      message: '请输入剧集名',
      trigger: 'blur'
    }
  ],
  index: [
    {
      required: true,
      message: '请输入剧集数',
      trigger: 'blur'
    },
    {
      type: 'integer',
      message: '剧集数必须是正整数',
      trigger: ['blur', 'change'],
      transform(value) {
        return value === '' ? 0 : Number(value)
      }
    }
  ],
  url: [
    {
      required: true,
      message: '请输入影视的播放源',
      trigger: 'blur'
    },
    {
      type: 'url',
      message: '请输入正确的URL链接地址',
      trigger: ['blur', 'change']
    }
  ]
})

watch(
  () => props.dialogTableVable,
  () => {
    form.value = props.dialogTableVable
  },
  { deep: true, immediate: true }
)
</script>

<style lang="scss" scoped>
.el-dialog {
  border-radius: var(--el-border-radius-small);
}
</style>
